package com.lideru.backstage.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.lideru.backstage.handler.NoAuth;
import com.lideru.backstage.utils.common.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/files")
public class FileController {
    @Value("${server.port}")
    private String port;

    private  String ip ="http://114.115.144.177:" ;

    @PostMapping("upload")
    @NoAuth
    public Result<?> upload(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String flag = IdUtil.fastSimpleUUID();
        String rootFilePath = System.getProperty("user.dir") + "/backstage/src/main/resources/files/" + flag+"_" + originalFilename;
        FileUtil.writeBytes(file.getBytes(), rootFilePath);
        return Result.success(ip + port + "/files/" + flag );
    }

    @PostMapping("/editor/upload")
    @NoAuth
    public JSON fileUpload(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        System.out.println(originalFilename);
        String flag = IdUtil.fastSimpleUUID();
        String rootFilePath = System.getProperty("user.dir") + "/backstage/src/main/resources/files/" + flag+"_" + originalFilename;
        FileUtil.writeBytes(file.getBytes(), rootFilePath);
        System.out.println("flag"+flag);
        String url = ip + port + "/files/" + flag ;
        JSONObject json = new JSONObject();
        json.set("errno",0);
        JSONArray array = new JSONArray();
        JSONObject data = new JSONObject();
        array.add(data);
        data.set("url",url);
        json.set("data",array);
        System.out.println(json);
        return json;
    }

    @GetMapping("/{flag}")
    @NoAuth
    public void getFiles(@PathVariable String flag , HttpServletResponse response)   {
        OutputStream os;
        String rootFilePath = System.getProperty("user.dir") + "/backstage/src/main/resources/files/";
        List<String> fileNames = FileUtil.listFileNames(rootFilePath);
        System.out.println("查询："+flag);
        String fileName = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");
        System.out.println("查询"+fileName);
        try {
            if (StrUtil.isNotEmpty(fileName)){
                response.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
                response.setContentType("application/octet-stream");
                byte[] bytes = FileUtil.readBytes(rootFilePath + fileName);
                os = response.getOutputStream();
                os.write(bytes);
                os.flush();
                os.close();
            }

        }catch (Exception e){
            System.out.println("文件下载失败！");
        }
    }
}
